package com.gmail.shazi199.satoriex.stage.image;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

import com.gmail.shazi199.satoriex.App;
import com.gmail.shazi199.satoriex.entity.Controllable;
import com.gmail.shazi199.satoriex.entity.Drawable;
import com.gmail.shazi199.satoriex.entity.Updated;
import com.gmail.shazi199.satoriex.entity.impl.Reimu;
import com.gmail.shazi199.satoriex.stage.SatoriStage;
import com.gmail.shazi199.satoriex.utils.Drawer;

public class TitleMenu implements Drawable, Updated, Controllable {

    private static final Log LOGGER = LogFactory.getLog(TitleMenu.class);
    
    private Texture texture;
    private Picture[] unSelect;
    private Picture[] selected;

    private int selectedItem = 0;

    @Override
    public void update() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void keyboardUpdate() {
        if (!Keyboard.getEventKeyState()) {
            switch (Keyboard.getEventKey()) {
            case Keyboard.KEY_UP:
                selectedItem = (selectedItem + 2) % 3;
                break;
            case Keyboard.KEY_DOWN:
                selectedItem = (selectedItem + 1) % 3;
                break;
            case Keyboard.KEY_RETURN:
                enterSelectedItem(selectedItem);
                break;
            default:
                break;
            }
        }
    }
    
    private void enterSelectedItem(int selectedItem) {
        switch (selectedItem) {
        case 0:
            App.getApp().setStage(new SatoriStage(new Reimu()));
            break;
        case 1:
            LOGGER.info("Player Data");
            break;
        case 2:
            App.getApp().exit();
            break;
        default:
            break;
        }
    }

    @Override
    public void draw() {
        for (int i = 0; i < 3; i++) {
            if (i == selectedItem) {
                Drawer.draw(texture, selected[i]);
            } else {
                Drawer.draw(texture, unSelect[i]);
            }
        }
    }

    public TitleMenu(int posX, int posY) {
        try {
            this.texture = TextureLoader.getTexture("PNG", App.class.getResourceAsStream("resource/image/titlemenu.png"));
        } catch (IOException e) {
            LOGGER.error("Load Texture error.", e);
            App.getApp().exit();
        }
        selected = new Picture[] {
                new Picture(posX, posY, 0, 0, 128, 32),
                new Picture(posX, posY + 32, 0, 128, 128, 32),
                new Picture(posX, posY + 64, 0, 224, 128, 32) };

        unSelect = new Picture[] {
                new Picture(posX, posY, 128, 0, 128, 32),
                new Picture(posX, posY + 32, 128, 128, 128, 32),
                new Picture(posX, posY + 64, 128, 224, 128, 32) };
    }
}